package com.yj.util;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletContext;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

public class ClassPathXmlResource implements Resource {

    Document document;

    Element rootElement;

    Iterator iterator;

    private ServletContext servletContext;


    public ClassPathXmlResource(String path, ServletContext servletContext) {



        SAXReader reader = new SAXReader();
        try{
            //URL resource = this.getClass().getClassLoader().getResource(path);
            InputStream resource = servletContext.getResourceAsStream(path);
            document = reader.read(resource);
            rootElement = document.getRootElement();
            iterator = rootElement.elementIterator();
        }catch (Exception e){
            throw new IllegalArgumentException("Invalid XML resource path: " + path, e);
        }
    }


    @Override
    public boolean hasNext() {
        return iterator.hasNext();
    }

    @Override
    public Object next() {
        return iterator.next();
    }
}
